package com.sanjiayi.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
public class RedisUtil {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    private static final String TOKEN_PREFIX = "user:token:";
    private static final String USER_PREFIX = "user:info:";

    /**
     * 存储用户token
     */
    public void setUserToken(Integer userId, String token, long timeout) {
        String key = TOKEN_PREFIX + userId;
        redisTemplate.opsForValue().set(key, token, timeout, TimeUnit.MILLISECONDS);
    }

    /**
     * 获取用户token
     */
    public String getUserToken(Integer userId) {
        String key = TOKEN_PREFIX + userId;
        Object value = redisTemplate.opsForValue().get(key);
        return value != null ? value.toString() : null;
    }

    /**
     * 存储用户信息
     */
    public void setUserInfo(Integer userId, Object userInfo, long timeout) {
        String key = USER_PREFIX + userId;
        redisTemplate.opsForValue().set(key, userInfo, timeout, TimeUnit.MILLISECONDS);
    }

    /**
     * 获取用户信息
     */
    public Object getUserInfo(Integer userId) {
        String key = USER_PREFIX + userId;
        return redisTemplate.opsForValue().get(key);
    }

    /**
     * 删除用户token
     */
    public void deleteUserToken(Integer userId) {
        String key = TOKEN_PREFIX + userId;
        redisTemplate.delete(key);
    }

    /**
     * 删除用户信息
     */
    public void deleteUserInfo(Integer userId) {
        String key = USER_PREFIX + userId;
        redisTemplate.delete(key);
    }
} 